package com.jse.service;


import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.jse.entity.Cache;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * ehcache 缓存组件类 缓存操作bean cacheName在ehcache.xml中配置
 */
@Component
public class EhcacheService implements Cache {

	@Resource
	public CacheManager cacheManager;

	@Override
	public Object get(String key) {
		net.sf.ehcache.Cache cache = cacheManager.getCache("obj");
		if (cache != null) {
			Element element = cache.get(key);
			if (element != null) {
				return element.getObjectValue();
			}
		}
		return null;
	}

	public Object get(String cacheName, Object key) {
		net.sf.ehcache.Cache cache = cacheManager.getCache(cacheName);
		if (cache != null) {
			Element element = cache.get(key);
			if (element != null) {
				return element.getObjectValue();
			}
		}
		return null;
	}

	public void put(String cacheName, Object key, Object value) {
		net.sf.ehcache.Cache cache = cacheManager.getCache(cacheName);
		if (cache != null) {
			cache.put(new Element(key, value));
		}
	}

	@Override
	public Object put(String key, Object value) {
		net.sf.ehcache.Cache cache = cacheManager.getCache("obj");
		if (cache != null) {
			cache.put(new Element(key, value));
		}
		return this;
	}

	@Override
	public void set(String key, Object value) {
		put(key, value);
	}

	public boolean remove(String cacheName, Object key) {
		net.sf.ehcache.Cache cache = cacheManager.getCache(cacheName);
		if (cache != null) {
			return cache.remove(key);
		}
		return false;
	}

	@Override
	public void remove(String key) {
		net.sf.ehcache.Cache cache = cacheManager.getCache("obj");
		if (cache != null) {
			cache.remove(key);
		}
	}

	public int size() {
		net.sf.ehcache.Cache cache = cacheManager.getCache("obj");
		if (cache != null) {
			return cache.getSize();
		}
		return 0;
	}

	@Override
	public boolean isEmpty() {
		net.sf.ehcache.Cache cache = cacheManager.getCache("obj");
		return cache == null;
	}

	@Override
	public boolean containsKey(Object key) {
		net.sf.ehcache.Cache cache = cacheManager.getCache("obj");
		return cache.get(key) != null;
	}
}